package com.atung.merchant.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

@RestController
@RequestMapping("/api/file")
@Api(tags = "文件中心")
public class FileDownloadController {
    private final static String projectRootPath = System.getProperty("user.dir") + "\\certificate\\";
    @GetMapping("/downloadTemplate")
    @ApiOperation("下载模版")
    public ResponseEntity<Resource> downloadTemplate(HttpServletResponse response) {

        String fileName = projectRootPath  + "menu_template.xlsx";
        File file = new File(fileName);
        if (!file.exists()) {
            throw new IllegalArgumentException("File not found");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", file.getName());
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.set("fileName", file.getName());
        Resource resource = new FileSystemResource(file);
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(file.length())
                .body(resource);

    }
}